--[[

This is a LUA bridge between MySQL proxy and shard-query

--]]

-- We serialize objects using json when sending them between MySQL proxy LUAspace and PHP code
json = require('json')

params = { ini = '/home/ec2-user/shard-query/shards.ini' }
set_binlog_format=0

function read_query(packet)
  read_query_error=false

  if packet:byte() == proxy.COM_QUERY then
    sql = packet:sub(2)
  end
  
  arg = json.encode( { sql = sql, params = params } )

  print('JSON encoded argument is: ' .. arg )


-- print ("The decoded table result:")
-- table.foreach(result,print)
-- print ("The decoded table result.three")
-- table.foreach(result.three, print)
   if string.match(string.lower(sql), 'select') then
     if set_binlog_format == 0 then
       proxy.queries:append(90,string.char(proxy.COM_QUERY) .. 'set binlog_format=statement', {resultset_is_needed=true})
       set_binlog_format = 1
     end 
     new_sql = "select gman_do('shard_query_worker','" .. arg .. "')" 
     
     proxy.queries:append(10,string.char(proxy.COM_QUERY) .. new_sql, {resultset_is_needed = true})
  
     return proxy.PROXY_SEND_QUERY

   else
     if set_binlog_format == 0 then
       proxy.queries:append(90,string.char(proxy.COM_QUERY) .. 'set binlog_format=statement', {resultset_is_needed=true})
       proxy.queries:append(100,string.char(proxy.COM_QUERY) .. sql, {resultset_is_needed=false})
       set_binlog_format = 1
       return proxy.PROXY_SEND_QUERY
     end 
   
   end 

   

end

function read_query_result(inj) 
  if inj.id == 10 then
    -- Get the results from the gearman process
    for row in inj.resultset.rows do
      data = row[1]
    end

    -- Decode the result, which is wrapped in a PHP structure, so we strip that off before decoding
    result = json.decode(string.gsub(string.sub(data,12,-3),'\\"','"'))
    
    -- If the gearman process says that we should simply execute the query on the directory, then do so:
    if(result.errors == false ) then 
      if #result.sql < 1 then 
	proxy.response = { type=proxy.MYSQLD_PACKET_OK, resultset = result.resultset }

	return proxy.PROXY_SEND_RESULT
      else 
        proxy.queries:append(20, string.char(proxy.COM_QUERY) .. result.sql, {resultset_is_needed = true})
        return proxy.PROXY_IGNORE_RESULT
      end  
    else
      proxy.response = {
      type        = proxy.MYSQLD_PACKET_ERR,
        errmsg      = json.encode(result.errors),
        -- errmsg      = 'THIS IS AN ERROR MESSAGE',
        errcode     = 1105,
        sqlstate    = 'HY000'
      }
      return proxy.PROXY_SEND_RESULT
    end
  end

  if inj.id == 90 then
    return proxy.PROXY_IGNORE_RESULT
  end 

end




